﻿Imports System.IO
Imports System.Threading
Imports System.Data.OleDb

Partial Public Class download
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim id1 As Integer = Request.QueryString("materialID")
        Dim filename As String = Request.QueryString("File")
        Dim dbconn = New OleDbConnection(ConfigurationManager.ConnectionStrings _
                               ("ConnectionString").ToString())
        dbconn.Open()


        ' Dim filename As String = getfileName(dbconn, Session("materialID"))
        'Response.WriteFile(filename, Server.MapPath("~/" + filename))

        Dim strRequest As String = filename '-- if something was passed to the file querystring
        If strRequest <> "" Then 'get absolute path of the file
            Dim path As String = Server.MapPath("~/" + strRequest) 'get file object as FileInfo
            Dim file As System.IO.FileInfo = New System.IO.FileInfo(path) '-- if the file exists on the server
            If file.Exists Then 'set appropriate headers
                Response.Clear()
                Response.AddHeader("Content-Disposition", "attachment; filename=" & file.Name)
                Response.AddHeader("Content-Length", file.Length.ToString())
                Response.ContentType = "application/octet-stream"
                Response.WriteFile(file.FullName)
                Response.End() 'if file does not exist
            Else
                Response.Write("This file does not exist.")
            End If 'nothing in the URL as HTTP GET
        Else
            Response.Write("Please provide a file to download.")
        End If
    End Sub

    Protected Function getfileName(ByVal dbconn As OleDbConnection, ByVal id1 As Integer)
        ' Dim materialID As Integer = 4
        id1 = Request.QueryString("materialID")
        'id1 = 4
        Dim averagesql As String = "SELECT File FROM MaterialCollection where materialID = " & id1
        Dim averagecmd As New OleDbCommand(averagesql, dbconn)
        Dim averageread = averagecmd.ExecuteReader()
        averageread.Read()
        Try
            Return averageread("File")
        Catch ex As Exception
            Return 0
        End Try
        dbconn.Close()
    End Function



End Class